/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-03-05 16:11:59
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-03-12 22:23:32
 * @FilePath: /lesson/Thread/Thread_package/thread_pack.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <unistd.h>
#include <pthread.h>

using namespace std;
namespace ThreadMoudle
{
    // 这个是线程要执行的方法
    typedef void (*func_t)(const std::string &name); // 函数指针类型

    class Thread
    {
    public:
        void Excute()
        {
            cout<<_name<<" is running "<<endl;
            _isrunning = true;
            _func  (_name);
            _isrunning = false;
        }

    public:
        Thread(const std::string &name,func_t func)// 传参只需要，传name和回调函数就好了
        :_name(name),_func(func)
        {
            cout<<"create "<<name<<" done "<<endl;
        }
        static void *ThreadRoutine(void* args)// 新线程都会执行的方法
        {
            Thread* self=static_cast<Thread*>(args);// 获得了当前对象
            self->Excute();
            return nullptr;
        }

        bool Start()
        {
            int n= ::pthread_create(&_tid,nullptr,ThreadRoutine,this);
            if(n!=0) return false;
            return true; 
        }
        std::string Status()// 每隔几秒钟，查看一下线程的状态！
        {
            if(_isrunning) return "isrunning";
            
            else return "sleep";
        }
        void Stop()
        {
            if(_isrunning)
            {
                ::pthread_cancel(_tid);
                _isrunning=false;
                cout<<_name<<" is stop"<<endl;

            }
        }
        void Join()
        {
            if(!_isrunning)
            {
                ::pthread_join(_tid,nullptr);
                cout<<_name<<" joined "<<endl;
            }
        }
        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {

        }

    private:
        std::string _name;
        pthread_t _tid;
        bool _isrunning;
        func_t _func; // 线程要执行的回调函数
    };
}